<template>
    <div class="cmt-container">
        <h3>发表评论</h3>
        <hr>
        <textarea placeholder="请输入要BB的内容（最多吐槽120字）" maxlength="120" v-model="msg"></textarea>
        
        <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>

        <div class="cmt-list">
            <div class="cmt-item" v-for="(item, index) in comments" :key="index">
                <div class="cmt-title">
                    第{{ index+1 }}楼&nbsp;&nbsp;用户：{{ item.user_name }}&nbsp;&nbsp;发表时间：{{ item.add_time | dateFormat}}
                </div>
                <div class="cmt-body">
                    {{item.content}}
                </div>
            </div>
        </div>

        <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
    </div>
</template>
<script>
export default {
    data(){
        return {
            comments: [],
            msg: ""
        }
    },
    created() {
        this.getComments()
        console.log("%c父组件传过来的id:","background-color:red",this.id);
    },
    methods: {
        getComments(){
            this.$http.get(this.$api+ '/comments').then(res =>{
                // this.comments = res.data.comments
                console.log(res);
                this.comments = this.comments.concat(res.data.comments)           
            })
        },
        getMore(){
            this.getComments();
        },
        postComment(){
            if(this.msg.trim().length === 0){
                // return Toast("评论内容不能为空!")
                alert("评论内容不能为空!");
                return
            }
            this.$http.post(this.$api + "/postComment").then(res =>{
                console.log(res);
                if(res){
                    var cmt = {
                        user_name: "匿名用户",
                        add_time: Date.now(),
                        content: this.msg
                    };
                    this.comments.unshift(cmt);
                    this.msg = "";
                }
            })
        }
    },
    props:["id"]
}
</script>
<style lang="scss" scoped>
.cmt-container {
    h3 {
        font-size: 16px;
    }
    textarea {
        font-size: 14px;
        height: 85px;
        margin: 0;
    }
    .cmt-list {
        .cmt-title {
            background-color: #9b9292;
            font-size: 14px;
        }
        .cmt-body {
            // font-size: 2em;
            text-indent: 2em;
            line-height: 35px;
        }
    }
    
}
</style>

